import {getUserInfo, updateMemberField} from '../../api/member.js';
import Util from '../../utils/util.js';
import {CACHE_USERINFO} from "../../config";

const app = getApp();
Page({

  /**
   * 页面的初始数据
   */
  data: {
    parameter: {
      title: "个人信息",
      isBack: true,
    },
    fields: {
      avatar: {title: "头像", required: true,},
      username: {title: "姓名", required: true,},
      gender: {
        title: "性别",
        type: "radio",
        range_key: 'title',
        required: true,
        options: [{id: 1, title: "男"}, {id: 2, title: "女"}]
      },
      mobile: {title: "手机号", type: "number", required: true,},
      address: {title: "所在地区", type: "region", required: true},
      // idcard_no: {title: "身份证号", required: true},
      // contact_name: {title: "紧急联系人",},
      // contact_phone: {title: "紧急联系人号码", type: "number",},
    }
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad(options) {
    const that = this;

    Util.chekWxLogin().then(res => {
      const userInfo = res.userInfo
      that.setData({userInfo: userInfo})

      wx.showLoading({title: '正在加载...'});
      getUserInfo().then(result => {
        let member = result.data || {};
        that.setData({
          member: member
        })
        let formData = this.data.formData || {},
          fields = that.data.fields;
        for (let k in fields) {
          if (fields[k].type == 'region') {
            formData[k] = fields[k].options = member[k] && member[k].split(' ') || [];
          } else {
            formData[k] = fields[k].default_val = member[k] || "";
          }
        }
        this.setData({
          formData: formData,
          fields: fields
        });
      }).catch(errmsg => {
        Util.Tips({title: errmsg})
      })

    }).then(() => {
      that.onLoadTabbar();
    }).catch(errmsg => {
    }).finally(() => {
      wx.hideLoading()
    })

  },

  onChooseImage(e) {
    const that = this;
    const key = "avatar";
    let member = that.data.member

    wx.chooseImage({
      count: 1,
      success(res) {
        const tempFilePaths = res.tempFilePaths;
        const url = `${app.globalData.url}/api/member/upload`;

        wx.showLoading({
          title: '正在上传...',
          mask: true,
        })
        for (let i = 0; i < tempFilePaths.length; i++) {
          wx.uploadFile({
            url: url,
            filePath: tempFilePaths[i],
            name: 'fileData',
            header: {
              token: wx.getStorageSync("cookie_token")
            },
            formData: {
              field_key: key
            },
            success(res) {
              const data = JSON.parse(res.data);
              member.avatar = data.data.path

              let fields = that.data.fields
              fields['avatar'].default_val = data.data.path || "";
              that.setData({
                member: member,
                fields: fields
              })
              wx.hideLoading()
            }
          });
        }
      },
      fail: function (error) {
      }
    });
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady() {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow() {

  },

  formSubmit(e) {
    const that = this;
    let formData = e.detail.value || {};
    let fields = that.data.fields;
    let msg = "";
    for (const k in fields) {
      if (k == 'avatar') {
        formData['avatar'] = fields[k].default_val || "";
      }
      if (!fields[k].required) continue;
      if (formData[k]) continue;
      msg = fields[k].title + "必填";
      break;
    }

    if (msg) {
      return Util.Tips({title: msg, hideMask: true});
    }
    wx.showLoading({title: "正在加载..."})
    updateMemberField(formData).then(res => {
      wx.setStorageSync("is_refresh_", 1);
      let userInfo = this.data.userInfo || {};

      userInfo.gender = formData.gender || 0;
      userInfo.avatar = formData.avatar || "";
      userInfo.username = formData.username || "";
      app.globalData.userInfo = userInfo;
      wx.setStorageSync(CACHE_USERINFO, JSON.stringify(userInfo));
      Util.Tips({title: "更新成功",}, {tab: 3});
    }).catch(errmsg => {
      Util.Tips({title: errmsg})
    }).finally(() => {
      wx.hideLoading()
    })
  },

  inputName(e) {
    const key = e.currentTarget.id;
    let formData = this.data.formData || {},
      fields = this.data.fields;
    formData[key] = fields[key].default_val = e.detail.value;
    this.setData({
      fields: fields,
      formData: formData
    })
  },

  radioChange(e) {
    const key = e.currentTarget.id;
    let formData = this.data.formData || {},
      fields = this.data.fields;
    formData[key] = fields[key].default_val = e.detail.value;
    this.setData({
      fields: fields,
      formData: formData
    })
  },

  bindRegionChange: function (e) { //选择地址
    const key = e.currentTarget.id;
    let formData = this.data.formData || {},
      fields = this.data.fields;

    fields[key].options = e.detail.value;
    if (e.detail.value[0] == e.detail.value[1]) {
      formData[key] = e.detail.value[1] + ' ' + e.detail.value[2];
    } else {
      formData[key] = e.detail.value.join(' ');
    }
    this.setData({
      fields: fields,
      formData: formData,
    })
  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide() {
  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload() {

  },

  onLoadTabbar: function () {//底部tabbar返回数据
    const that = this
    Util.checkIphone().then(res => {//检查是否是iphone x/11等
      that.setData({
        isIphoneX: res,
      })
    }).finally(() => {
      wx.createSelectorQuery().in(that).select('.weui-footer')
        .boundingClientRect(function (rect) {
          that.setData({
            bottom: parseInt(rect.height)
          })
        }).exec()
    });
  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh() {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom() {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage() {

  }
})